package com.base.controller.czb.czbapi;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.base.controller.utils.CZB.CZBTokenUtils;
import com.base.po.czb_sdk.Gas;
import com.base.po.czb_sdk.GasOilprice;
import com.base.po.param.NetState;
import com.base.po.voip.Subscribers;
import com.base.po.voip.Users;
import com.base.service.CZB.GasOilpriceService;
import com.base.service.CZB.GasService;
import com.base.service.SubscribersService;
import com.base.service.UsersService;
import com.base.utils.Produce;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/getGasNews")
public class GasShopNews {
    @Autowired
    UsersService usersService;
    @Autowired
    SubscribersService subscribersService;
    @Autowired
    GasService gasService;
    @Autowired
    GasOilpriceService gasOilpriceService;

    @RequestMapping(value = "/getAllGasList", method = {RequestMethod.POST, RequestMethod.GET})
    public @ResponseBody
    NetState getAllGasList(String mobile, String parentId) {
        NetState netState = new NetState();
        if (parentId == null || parentId.equals("") || mobile == null || mobile.equals("")) {
            netState.setErrorCode(NetState.PARAMS_ERROR);
            netState.setData("请填写参数！");
            return netState;
        }
        Users users = usersService.selectByPrimaryKey(parentId);
        List<Subscribers> subscribersList = subscribersService.selectBySub(mobile, parentId);
        if (users == null || subscribersList.size() <= 0) {
            netState.setErrorCode(NetState.PARAMS_ERROR);
            netState.setData("参数异常");
            return netState;
        }

        Subscribers sub = subscribersList.get(0);
        Long timeStamp = new Date().getTime();
        try {
            String token = CZBTokenUtils.createToken(timeStamp, sub.getMobile());
            JSONObject t1 = JSONObject.parseObject(token);
            JSONObject data = t1.getJSONObject("result");
            Object tokenResult = data.get("token");
            String result = CZBTokenUtils.getAllGasInfo(timeStamp, sub.getMobile(), tokenResult.toString());

            JSONObject r1 = JSONObject.parseObject(result);
            JSONArray jsonArray = (JSONArray) r1.get("result");
            jsonArray.forEach(item -> {
                int code = insertGas(item);
            });

        } catch (Exception e) {
            e.printStackTrace();
            netState.setData("调用权限接口发生错误");
            netState.setErrorCode(NetState.FEAILED);
        }
        return netState;
    }

    /**
     * @Date: 2019/11/15 10:10
     * @Description: 插入油站和油枪信息
     */
    private int insertGas(Object item) {
        System.out.println("开始插入油站信息");
        GasService gasService = this.gasService;
        JSONObject gas = JSONObject.parseObject(item.toString());
        String gasid = gas.getString("gasId");
        String gasName = gas.getString("gasName");
        String gasType = gas.getString("gasType");
        String gasLogoBig = gas.getString("gasLogoBig");
        String gasLogoSmall = gas.getString("gasLogoSmall");
        String gasAddress = gas.getString("gasAddress");
        BigDecimal gasAddressLongitude = new BigDecimal(gas.getString("gasAddressLongitude"));
        BigDecimal gasAddressLatitude = new BigDecimal(gas.getString("gasAddressLatitude"));
        String provinceCode = gas.getString("provinceCode");
        String cityCode = gas.getString("cityCode");
        String countyCode = gas.getString("countyCode");
        String provinceName = gas.getString("provinceName");
        String cityName = gas.getString("cityName");
        String countyName = gas.getString("countyName");

        Integer isInvoice = Integer.parseInt(gas.get("isInvoice").toString());
        String companyId = gas.get("companyId").toString();
        Gas gas1 = new Gas(gasid, gasName, gasType, gasLogoBig, gasLogoSmall, gasAddress, gasAddressLongitude, gasAddressLatitude, provinceCode,
                cityCode, countyCode, provinceName, cityName, countyName, isInvoice, companyId);

        //判断是否已经存在
        int code = 0;
        Gas gasAlready = gasService.selectByPrimaryKey(gas1.getGasid());
        if (gasAlready != null) {
            code = gasService.updateByPrimaryKeySelective(gas1);
        } else {
            code = gasService.insertSelective(gas1);
        }

        String gasId = gas1.getGasid();
        if (code > 0) {
            JSONArray oilpriceList = (JSONArray) gas.get("oilPriceList");
            oilpriceList.forEach(oilprice -> {
                insertOilPrice(gasId, oilprice);
            });
        }
        System.out.println("油站信息录入完成");
        return code;
    }

    /**
     * @Date: 2019/11/15 10:22
     * @Description: 插入油枪信息
     */
    public int insertOilPrice(String gasId, Object oilprice) {
        System.out.println("开始插入一条油枪信息");
        GasOilpriceService gasOilpriceService = this.gasOilpriceService;

        JSONObject oilPrice = JSONObject.parseObject(oilprice.toString());
        String oilNo = oilPrice.getString("oilNo");
        String oilName = oilPrice.getString("oilName");
        String oilType = oilPrice.getString("oilType");
        String priceYfq = oilPrice.getString("priceYfq");
        String priceGun = oilPrice.getString("priceGun");
        String priceOfficial = oilPrice.getString("priceOfficial");
        String ID = Produce.getUUID();
        GasOilprice gasOilprice = new GasOilprice(ID, oilNo, oilName, oilType, new BigDecimal(priceYfq), new BigDecimal(priceGun), new BigDecimal(priceOfficial), gasId);

        //插入油枪信息，判断是否存在
        int priceCode = 0;
        GasOilprice gasOilprice1 = gasOilpriceService.selectByPrimaryKey(gasOilprice.getId());
        if (gasOilprice1 != null) {
            priceCode = gasOilpriceService.updateByPrimaryKeySelective(gasOilprice1);
        } else {
            priceCode = gasOilpriceService.insertSelective(gasOilprice);
        }

        if (priceCode > 0) {
            System.out.println("油枪信息录入成功");
            return 1;
        }
        return 0;
    }

//    @Scheduled(cron = "0 0/1 * * * ?")
//    public void gasInfo(){
//        System.out.println("读取油站信息");
//
//        Connection conn = null;
//        PreparedStatement pstm = null;
//
//        try {
//            Class.forName("com.mysql.jdbc.Driver");
//            conn = DriverManager.getConnection(CommUrls.JDBC, CommUrls.JDBC_USER, CommUrls.JDBC_PASSWORD);
//
//            String token = CZBTokenUtils.createToken(Produce.getNowDate().getTime(), "18055603791");
//            JSONObject t1 = JSONObject.parseObject(token);
//            JSONObject data = t1.getJSONObject("result");
//            Object tokenResult = data.get("token");
//            String gasInfoResult = CZBTokenUtils.getAllGasInfo(Produce.getNowDate().getTime(), "18055603791", tokenResult.toString());
//
//            Map<String, Object> infoMap = new HashedMap();
//            infoMap.put("result", GasInfoResult.class);
//            GasInfo gasInfo = (GasInfo) net.sf.json.JSONObject.toBean(net.sf.json.JSONObject.fromObject(gasInfoResult), GasInfo.class, infoMap);
//            if (gasInfo.getCode() == 200){
//                List<GasInfoResult> infoResulte= gasInfo.getResult();
//                if (infoResulte != null && infoResulte.size() > 0){
//                    for (GasInfoResult result : infoResulte){
//                        Map<String, Object> resultMap = new HashedMap();
//                        resultMap.put("oilPriceList", GasInfoOilPriceList.class);
//                        GasInfoResult info = (GasInfoResult) net.sf.json.JSONObject.toBean(net.sf.json.JSONObject.fromObject(result), GasInfoResult.class, infoMap);
//                        if (info != null){
//                            String gasOilInsert = " INSERT INTO gas (gasId, gasName, gasType, gasLogoBig, gasLogoSmall, gasAddress, gasAddressLongitude, gasAddressLatitude, provinceCode, cityCode, countyCode, provinceName, cityName, countyName, isInvoice, companyId) VALUES (?, ?, ?, ? , ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
//                            pstm = conn.prepareStatement(gasOilInsert, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
//                            conn.setAutoCommit(false);
//                            pstm.setString(1, info.getGasId());
//                            pstm.setString(2, info.getGasName());
//                            pstm.setString(3, String.valueOf(info.getGasType()));
//                            pstm.setString(4, info.getGasLogoBig());
//                            pstm.setString(5, info.getGasLogoSmall());
//                            pstm.setString(6, info.getGasAddress());
//                            pstm.setBigDecimal(7, new BigDecimal(info.getGasAddressLongitude()));
//                            pstm.setBigDecimal(8, new BigDecimal(info.getGasAddressLatitude()));
//                            pstm.setString(9, String.valueOf(info.getProvinceCode()));
//                            pstm.setString(10, String.valueOf(info.getCityCode()));
//                            pstm.setString(11, String.valueOf(info.getCountyCode()));
//                            pstm.setString(12, info.getProvinceName());
//                            pstm.setString(13, info.getCityName());
//                            pstm.setString(14, info.getCountyName());
//                            pstm.setInt(15, info.getIsInvoice());
//                            pstm.setString(16, String.valueOf(info.getCompanyId()));
//                            pstm.addBatch();
//
////                            GasOilprice gasOil = gasOilpriceService.selectByPrimaryKey(info.getGasId());
////                            List<GasInfoOilPriceList> oilPrice = info.getOilPriceList();
////                            for (GasInfoOilPriceList price : oilPrice){
////
////                            }
//                        }else {
//                            String gasOilUpdate = " UPDATE gas SET gasName=?, gasType=?, gasLogoBig=?, gasLogoSmall=?, gasAddress=?, gasAddressLongitude=?, gasAddressLatitude=?, provinceCode=?, cityCode=?, countyCode=?, provinceName=?, cityName=?, countyName=?, isInvoice=?, companyId=? WHERE gasId=?";
//                            pstm = conn.prepareStatement(gasOilUpdate, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
//                            conn.setAutoCommit(false);
//                            pstm.setString(1, info.getGasName());
//                            pstm.setString(2, String.valueOf(info.getGasType()));
//                            pstm.setString(3, info.getGasLogoBig());
//                            pstm.setString(4, info.getGasLogoSmall());
//                            pstm.setString(5, info.getGasAddress());
//                            pstm.setBigDecimal(6, new BigDecimal(info.getGasAddressLongitude()));
//                            pstm.setBigDecimal(7, new BigDecimal(info.getGasAddressLatitude()));
//                            pstm.setString(8, String.valueOf(info.getProvinceCode()));
//                            pstm.setString(9, String.valueOf(info.getCityCode()));
//                            pstm.setString(10, String.valueOf(info.getCountyCode()));
//                            pstm.setString(11, info.getProvinceName());
//                            pstm.setString(12, info.getCityName());
//                            pstm.setString(13, info.getCountyName());
//                            pstm.setInt(14, info.getIsInvoice());
//                            pstm.setString(15, String.valueOf(info.getCompanyId()));
//                            pstm.setString(16, info.getGasId());
//                            pstm.addBatch();
//                        }
//                    }
//                    pstm.executeBatch();
//                    conn.commit();
//                }
//            }
//        }catch (Exception e) {
//            e.printStackTrace();
//            throw new RuntimeException(e);
//        } finally {
//            if (pstm != null) {
//                try {
//                    pstm.close();
//                } catch (SQLException e) {
//                    e.printStackTrace();
//                    throw new RuntimeException(e);
//                }
//            }
//            if (conn != null) {
//                try {
//                    conn.close();
//                } catch (SQLException e) {
//                    e.printStackTrace();
//                    throw new RuntimeException(e);
//                }
//            }
//        }
//    }
}
